<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Thu, 1 Jan 1970 01:00:00 GMT"); // Date in the past
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
ini_set('log_errors', '1');
ini_set('error_log', 'php_error.log');
ini_set('display_errors', '1');

include_once("file.common.php");
autoHeader();
authenticate($validCredentials);

$source = req('source', '');
$file = req('file', '');
$width = req('width', 100);

$result = TRUE;
$cmd = '';
$log = array();
$tmp = '';

$isHttp = stripos($source, "http://") === 0 || stripos($source, "https://") === 0;

if ($isHttp)
{
	@mkdir("tmp");
	$pi = pathinfo($source);
	$tmp = "tmp/" . $pi["basename"];
	copy($source, $tmp);
	$source = $tmp;
}

function imgResize($file1,$file2,$width,$height) {
	global $cmd;
	$wh = $width . ($height ? 'x' . $height . '!' : '');
	$cmd .= "convert \"$file1\" -resize $wh \"$file2\"\r\n";
	unlink($file2);
	$isz = getimagesize($file1);
	if ($isz[0] > $width)
		exec("convert " . '"' . $file1 . '"' . " -resize $wh " . '"' . $file2 . '"');
	else
		copy($file1, $file2);
	return file_exists($file2);
}

$result = imgResize($source, $file, $width);

if ($isHttp)
{
	unlink($tmp);
}

if ($callback)
	$ee .= "$callback({\n";
else
	$ee .= "{\n";
$ee .= '"result":' . json_encode($result) . ",\n";
$ee .= '"cmd":' . json_encode($cmd) . ",\n";
$ee .= '"log":' . json_encode($log) . ",\n";
if ($devserver) {
	$ee .= '"cwd":' . json_encode(getcwd()) . ",\n";
	$ee .= '"root":' . json_encode($_SERVER['DOCUMENT_ROOT']) . ",\n";
}
$ee .= '"end":true' . "\n";
if ($callback)
	$ee .= "})";
else
	$ee .= "}";
echo $ee;

?>